from PIL import Image, ImageDraw, ImageFont
import random
from io import BytesIO
import os


# 生成验证码
def get_validCode_img(request):
    # Path 1：可以打开open()打开图片，用HttpResponse返回
    # Path 2：PIL生成图片
    # 随机生成颜色
    bg_color = [random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)]
    img = Image.new("RGB", (90, 40), color=(bg_color[0], bg_color[1], bg_color[2]))

    # 通过open()是对磁盘进行操作，太慢了，通过BytesIO优化，数据从内存即可读取
    # with open(img_name, "rb") as f:
    #     dataset = f.read()
    font = ImageFont.truetype(f"{os.getcwd()}/web/static/fonts/Ubuntu-R.ttf", size=26)
    draw = ImageDraw.Draw(img)

    # 保存生成的验证码
    valid_code_str = ""

    # 循环生成4个随机字符+数字
    for i in range(4):
        num = str(random.randint(0, 9))     # 数字0-9
        small_char = chr(random.randint(65, 90))    # ASCII的A-Z
        big_char = chr(random.randint(97, 122))     # ASCII的a-z
        rand_char = random.choice([num, small_char, big_char])
        draw.text((i*22+5, 5), rand_char, (0, 0, 0), font=font)
        # 保存
        valid_code_str += rand_char

    # 给验证码模糊处理，两个循环次数越多越不好识别
    width = 200
    height = 40
    # 画影响识别的线
    for i in range(5):
        x1 = random.randint(0, width)
        x2 = random.randint(0, width)
        y1 = random.randint(0, height)
        y2 = random.randint(0, height)
        draw.line((x1, x2, y1, y2), fill=(255, 255, 255))
    # 画影响识别的圆点
    for i in range(75):
        draw.point([random.randint(0, width), random.randint(0, height)], fill=(255, 255, 255))
        x = random.randint(0, width)
        y = random.randint(0, height)
        draw.arc((x, y, x+4, y+4), 0, 90, fill=(255, 255, 255))

    # 将验证码保存到Cookie当中
    request.session["valid_code_str"] = valid_code_str

    # 内存读写操作
    f = BytesIO()
    img.save(f, format="png")
    data = f.getvalue()

    return data
